layui.use(['table', 'admin', 'ax', 'func', 'form'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var form = layui.form;
    var func = layui.func;

    /**
     * 管理
     */
    var ContentArticle = {
        tableId: "contentArticleTable"
    };

    /**
     * 初始化表格的列
     */
    ContentArticle.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: ''},
            {field: 'title', sort: true, title: '标题'},
            {field: 'author', sort: true, title: '作者'},
            {field: 'areaNames', sort: true, title: '地区'},
            {field: 'labelNames', sort: true, title: '标签'},
            {field: 'description', sort: true, title: '描述'},
            {field: 'textContent', sort: true, title: '文章内容'},
            {field: 'originate', sort: true, title: '来源'},
            {field: 'serviceAge', sort: true, title: '服役年限'},
            {field: 'clickQuantity', sort: true, title: '点击量'},
            {field: 'sortNo', sort: true, title: '排序'},
            {
                field: 'imageUrl', sort: true, title: '图片', templet: function (d) {
                    if (!d.imageUrl) {
                        return ''
                    }
                    return '<img class="layui-upload-img" style="height: 100px;width: 100px" src="' + d.imageUrl + '">'
                }
            },
            {
                field: 'status', sort: true, title: '状态', templet: function (d) {
                    if (d.status === 0) {
                        return "禁用"
                    } else {
                        return "启用"
                    }
                }
            },
            {field: 'createTime', sort: true, title: '创建时间', width: 160},
            {field: 'updateTime', sort: true, title: '修改时间', width: 160},
            // {field: 'createUser', sort: true, title: '创建人'},
            // {field: 'deleteFlag', sort: true, title: '0 正常 1,删除'},
            // {field: 'updateUser', sort: true, title: '修改人'},
            {align: 'center', toolbar: '#tableBar', title: '操作', fixed: 'right', width: 160}
        ]];
    };

    /**
     * 点击查询按钮
     */
    ContentArticle.search = function () {
        var queryData = getParam();

        table.reload(ContentArticle.tableId, {
            where: queryData, page: {curr: 1}
        });
    };

    /**
     * 获取查询参数
     */
    function getParam() {
        var queryData = {};
        queryData['status'] = $('#status').val();
        queryData['author'] = $('#author').val();
        queryData['title'] = $('#title').val();
        queryData['categoryId'] = $('#categoryId').val();
        console.log("queryData", queryData)
        return queryData;
    }


    /**
     * 跳转到添加页面
     */
    ContentArticle.jumpAddPage = function () {
        window.location.href = Changein.ctxPath + '/contentArticle/add'
    };

    /**
     * 跳转到编辑页面
     *
     * @param data 点击按钮时候的行数据
     */
    ContentArticle.jumpEditPage = function (data) {
        window.location.href = Changein.ctxPath + '/contentArticle/edit?id=' + data.id
    };

    /**
     * 删除
     */
    var deleteBatchLock = false;
    ContentArticle.deleteBatch = function () {
        if (!deleteBatchLock) {
            var checkRows = table.checkStatus(Sample.tableId);
            if (checkRows.data.length == 0) {
                Changein.error("请选择要删除的数据");
                return false;
            }
            var arr = [];
            var tabData = checkRows.data;
            for (var i = 0; i < tabData.length; i++) {
                if (tabData[i].audit != 1) {
                    arr.push(tabData[i].id);
                }
            }
            if (arr.length == 0) {
                Changein.error("选中数据全部已审核，请选择未审核的数据");
                return false;
            }
            var operation = function () {
                deleteBatchLock = true;
                var ajax = new $ax(Changein.ctxPath + "/contentArticle/batchDeleteByIds", function (data) {
                    if (data.code != 200) {
                        Changein.error("删除失败！" + data.message);
                    } else {
                        Changein.success("删除成功！");
                    }
                    deleteBatchLock = false;
                    table.reload(ContentArticle.tableId);
                }, function (data) {
                    deleteBatchLock = false;
                    Changein.error("删除失败！" + data.responseJSON.message)
                });
                ajax.set({"ids": arr.toString()});
                ajax.start();
            }
            Changein.confirm("是否删除?", operation);
        } else {
            Changein.error("正在删除中");
        }
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    ContentArticle.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Changein.ctxPath + "/contentArticle/delete", function (data) {
                Changein.success("删除成功!");
                table.reload(ContentArticle.tableId);
            }, function (data) {
                Changein.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Changein.confirm("是否删除?", operation);
    };
    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    var deleteLock = false;
    ContentArticle.onDeleteItem = function (data) {
        if (data.audit == 1) {
            Changein.error("选中数据已审核，请选择未审核的数据");
            return false;
        }
        var operation = function () {
            deleteLock = true;
            var ajax = new $ax(Changein.ctxPath + "/contentArticle/delete", function (data) {
                deleteLock = false;
                if (data.code != 200) {
                    Changein.error("删除失败！" + data.message);
                } else {
                    Changein.success("删除成功！");
                }
                table.reload(ContentArticle.tableId);
            }, function (data) {
                deleteLock = false;
                Changein.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        if (!deleteLock) {
            Changein.confirm("是否删除?", operation);
        } else {
            Changein.error("正在删除中");
        }
    };

    /**
     * 点击删除
     *
     * @param data 点击重建索引
     */
    var reIndexLock = false;
    ContentArticle.reIndex = function (id) {
        var operation = function () {
            deleteLock = true;
            var ajax = new $ax(Changein.ctxPath + "/contentArticle/reIndex", function (data) {
                deleteLock = false;
                if (data.code != 200) {
                    Changein.error("更新失败！" + data.message);
                } else {
                    Changein.success("更新成功！");
                }
                table.reload(ContentArticle.tableId);
            }, function (data) {
                deleteLock = false;
                Changein.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", id);
            ajax.start();
        };
        if (!reIndexLock) {
            Changein.confirm("是否重建索引", operation);
        } else {
            Changein.error("正在重建索引众...");
        }
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + ContentArticle.tableId,
        url: Changein.ctxPath + '/contentArticle/list',
        page: true,
        height: "full-130",
        cellMinWidth: 100,
        cols: ContentArticle.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        ContentArticle.search();
    });   // 搜索按钮点击事件
    $('#reIndex').click(function () {
        ContentArticle.reIndex();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        ContentArticle.jumpAddPage();
    });
    // 删除
    $("#btnDel").click(function () {
        ContentArticle.deleteBatch();
    });

    // 工具条点击事件
    table.on('tool(' + ContentArticle.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            ContentArticle.jumpEditPage(data);
        } else if (layEvent === 'delete') {
            ContentArticle.onDeleteItem(data);
        }
    });

    //---------------------分类-----------------------------------
    var categoryAjax = new $ax(Changein.ctxPath + "/contentCategory/list")
    categoryAjax.set("limit", 1000)
    categoryAjax.set("associationType", 2)
    let categoryRes = categoryAjax.start();
    if (isResultOK(categoryRes)) {
        let categorySelect = $("#categoryId")
        categoryRes.data.forEach(function (item) {
            console.log(item)
            categorySelect.append(" <option value=\"" + item.id + "\"> " + item.assortName + "</option>")
        })
        form.render()
    } else {
        Changein.error("获取分类列表失败");
    }
});
